<p>When encrypting data with the Cipher Block Chaining (CBC) mode an Initialization Vector (IV) is used to randomize the encryption, ie under a given
key the same plaintext doesn’t always produce the same ciphertext. The IV doesn’t need to be secret but should be unpredictable to avoid
"Chosen-Plaintext Attack".</p>
<p>To generate Initialization Vectors, NIST recommends to use a secure random number generator.</p>
<h2>Noncompliant Code Example</h2>
<pre>
public void encrypt(String key, String plainText) throws GeneralSecurityException {
    byte[] bytesIV = "7cVgr5cbdCZVw5WY".getBytes(StandardCharsets.UTF_8); // secondary

    GCMParameterSpec iv = new GCMParameterSpec(128,bytesIV);  // secondary
    SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); // Noncompliant
  }
</pre>
<h2>Compliant Solution</h2>
<pre>
public void encrypt(String key, String plainText) throws GeneralSecurityException {
    SecureRandom random = new SecureRandom();
    byte[] bytesIV = new byte[16];
    random.nextBytes(bytesIV); // Random initialization vector

    GCMParameterSpec iv = new GCMParameterSpec(128, bytesIV);
    SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
  }
</pre>
<h2>See</h2>
<ul>
  <li> <a href="https://owasp.org/Top10/A02_2021-Cryptographic_Failures/">OWASP Top 10 2021 Category A2</a> - Cryptographic Failures </li>
  <li> <a href="https://www.owasp.org/index.php/Top_10-2017_A3-Sensitive_Data_Exposure">OWASP Top 10 2017 Category A3</a> - Sensitive Data Exposure
  </li>
  <li> <a href="https://mobile-security.gitbook.io/masvs/security-requirements/0x08-v3-cryptography_verification_requirements">Mobile AppSec
  Verification Standard</a> - Cryptography Requirements </li>
  <li> <a href="https://owasp.org/www-project-mobile-top-10/2016-risks/m5-insufficient-cryptography">OWASP Mobile Top 10 2016 Category M5</a> -
  Insufficient Cryptography </li>
  <li> <a href="https://cwe.mitre.org/data/definitions/329">MITRE, CWE-329</a> - Not Using an Unpredictable IV with CBC Mode </li>
  <li> <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf">NIST, SP-800-38A</a> - Recommendation for Block Cipher
  Modes of Operation </li>
  <li> Derived from FindSecBugs rule <a href="https://find-sec-bugs.github.io/bugs.htm#STATIC_IV">STATIC_IV</a> </li>
</ul>

